package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;

import com.itheima.reggie.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    //登陆
    @Override
    public ResultInfo login(String username, String password) {
        //调用mapper查询,不存在返回提示
     Employee employee =  employeeMapper.findByName(username);
        if (employee == null) {
           return ResultInfo.error("用户名不存在！");
        }

        //存在判断密码
        String passwordMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordMd5, employee.getPassword())) {
            return ResultInfo.error("密码错误，请重新输入！");
        }

        //检测用户状态
        if (employee.getStatus() == Employee.STATUS_DISABLE) {
            return ResultInfo.error("账号已禁用！");
        }

        //返回登陆成功
        return ResultInfo.success(employee);
    }


    //查询列表
    @Override
    public List<Employee> findList(String name) {
         return employeeMapper.findList(name);
    }

    //保存
    @Override
    public void save(Employee employee) {
        //补齐参数
        employee.setId(IdUtil.getSnowflake(1, 1).nextId()); //雪花算法生成id
        employee.setPassword(SecureUtil.md5("123")); //设置默认密码
        employee.setStatus(Employee.STATUS_ENABLE); //默认激活

       /* //时间
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        //操作人
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/

        //调用mapper
        employeeMapper.save(employee);
    }

        //根据id查询
    @Override
    public Employee findById(long id) {

        //调用mapper查询
       return employeeMapper.findById(id);
    }

        //修改
    @Override
    public void update(Employee employee) {

      /*  //重新赋值
        employee.setUpdateUser(1L);
        employee.setUpdateTime(new Date());
*/
        //调用mapper修改
        employeeMapper.update(employee);
    }
}
